<!--
 * @Descripttion: 公告管理
 * @version:
 * @Author: 张文韬
 * @Date: 2020-10-13 11:49:35
 * @LastEditors: 穆宏宇
 * @LastEditTime: 2020-11-26 18:16:05
-->
<template>
  <div class="bigDiv">
    <div class="control-box">
      <!-- control 操作区 START -->
      <e-control :search-form-options="formOptions"
                 :search-label-width="searchLabelWidth"
                 :search-refresh-show="true"
                 :btns="btns"
                 :search-show="true"
                 :operation-show="true"
                 @on-search="searchControlHandle"
                 @on-refresh="refreshControlHandle"
                 @change-height="changeControlHeight"
                 @on-insert="insertControlHandle"></e-control>
      <!-- control 操作区 END -->
    </div>
    <div class="table-box">
      <!-- table 数据表格 START -->
      <e-table :data="tableData"
               :columns="columns"
               stripe
               border
               height="calc(100vh - 340px)"
               style="width: 100%"
               @selection-change="changeTableSelectData"
               :current="pageData.pageNum"
               :total="pageData.total"
               @page-size-change="changePageSize"
               @page-current-change="changePageCurrent">
        <template slot-scope="{scope}"
                  slot="operation">
          <el-button @click="updateTableHandle(scope.row)"
                     type="warning"
                     size="mini"
                     plain>编辑</el-button>
          <el-button @click="deleteTableHandle(scope.row)"
                     type="warning"
                     size="mini"
                     plain>删除</el-button>
        </template>
      </e-table>
      <!-- table 数据表格 END -->
    </div>
    <!-- editDialog 编辑弹窗 START -->
    <el-dialog :title="editDialogTitle"
               :visible.sync="editDialogShow"
               :close-on-click-modal="false"
               :close-on-press-escape="false"
               @close="closeDialog"
               width="50%">
      <e-form ref="dialogForm"
              :form-options="editFormOptions"
              :form-label-width="editFormLabelWidth"
              :form-rules="editFormRules"
              :form-data-current="dialogFormCurrent"></e-form>
      <el-upload
          class="uploadImage"
          :action="fileUrl"
          :data="{ objectName: 'notice' }"
          :headers="fileConfig"
          :show-file-list="false"
          accept=".jpg,.jpeg,.png,.gif"
          multiple
          :file-list="imageList"
          :before-upload="loadingFn"
          :on-success="handleImgSuccess"
          :on-error="handleImgError"
      >
      </el-upload>
      <div class="edit-box editor-box-height" v-loading="loading">
        <quill-editor
            ref="editorText"
            v-model="content"
            class="myQuillEditor myQuillEditor-height"
            :options="editorOption"
        />
      </div>
      <el-upload
          class=""
          :data="{ objectName: 'notice'}"
          :headers="fileConfig"
          :action="fileUrl"
          multiple
          :file-list="fileList"
          :on-remove="handleRemove"
          :on-success="handleUploadSuccess"
          :on-error="handleUploadError"
          :before-upload="beforeUpload"
          :on-exceed="handleExceed">
        <el-button size="small" type="primary">上传附件</el-button>
        <div slot="tip" class="el-upload__tip">
          <p style="color: red">请上传一个小于500M的附件</p>
        </div>
      </el-upload>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="cancelDialogDataHandle">取 消</el-button>
        <el-button type="primary"
                   @click="saveDialogDataHandle">保 存</el-button>
      </span>
    </el-dialog>
    <!-- editDialog 编辑弹窗 END -->
  </div>
</template>
<script>

// 富文本相关
import { quillEditor } from "vue-quill-editor"
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";

import eControl from '@/components/e-control'
import eForm from '@/components/e-form'
import { formOptions, btns } from './control'
import columns from './columns'
import { editFormOptions, editFormRules } from './form'
import { getPlanList, insertPlanNotice, editPlanNotice, deletePlanNotice } from '@/api/admin.api'
import { beforeUpload } from '@/util/common'
// 上传文件
import fileUpdata from '@/api/file.config'
import { deleteFile, getFileInfo } from '@/api/common.api'

  import moment from 'moment'
import { Base64 } from "js-base64";
// 工具栏配置
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [{ header: 1 }, { header: 2 }], // custom button values
  [{ list: "ordered" }, { list: "bullet" }],
  [{ script: "sub" }, { script: "super" }], // superscript/subscript
  [{ indent: "-1" }, { indent: "+1" }], // outdent/indent
  [{ direction: "rtl" }], // text direction

  [{ size: ["small", false, "large", "huge"] }], // custom dropdown
  [{ header: [1, 2, 3, 4, 5, 6, false] }],

  [{ color: [] }, { background: [] }], // dropdown with defaults from theme
  [{ font: [] }],
  [{ align: [] }],
  ["link", "image"],
  ["clean"], // remove formatting button
];

export default {
  name: 'announcement-manager',
  components: {
    eControl,
    eForm,
    quillEditor
  },
  props: {},
  data () {
    return {
      formOptions,
      searchLabelWidth: '100px',
      btns,
      columns,
      editFormOptions,
      editFormLabelWidth: '100px',
      editFormRules,

      // 编辑框是否展示
      editDialogShow: false,
      // 编辑框类型 0:新增;1:修改;
      editDialogType: 0,
      // 编辑框表单数据
      dialogFormCurrent: {},
      // 查询表单
      searchFormData: {},
      // 控制区高度
      controlHeight: 0,
      // 表格数据
      tableData: [],
      // 分页数据
      pageData: {
        // 当前分页
        pageNum: 1,
        // 分页条数
        pageSize: 10,
        // 数据总数
        total: 0
      },
      // 表格选中数据
      tableSelectData: [],
      // 附件列表
      fileList: [],
      fileConfig: {},
      // fileUrl: '',
	  fileUrl: "/vapi/file/uploadfile",
      // 富文本编辑相关
      content: "",
      id: "",
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: (value) => {
                if (value) {
                  document.querySelector(".uploadImage input").click();
                } else {
                  this.quill.format("image", false);
                }
              },
              upload: (value) => {
                if (value) {
                  alert("自定义文件上传");
                }
              },
            },
          },
        },
      },
      oldData: "",
      loading: false,
      imageList: []
    }
  },
  watch: {},
  computed: {

    // 组合查询条件和分页
    searchData () {
      const { pageNum, pageSize } = this.pageData
      return { ...this.searchFormData, size: pageSize, current: pageNum, noticeType: 3 }
      // return Object.assign(this.searchFormData,{size: pageSize},{current:pageNum})
    },
    // 表单实例
    dialogForm () {
      return this.$refs.dialogForm
    },
    //表格最大高度
    tableMaxHeight () {
      return window.innerHeight - this.controlHeight - 160
    },
    // 编辑框标题
    editDialogTitle () {
      return this.editDialogType === 0 ? '新增' : '编辑'
    },

    // 富文本编辑
    oldUrls() {
      let temp = [];
      if (this.oldData) {
        let imgReg = /<img.*?(?:>|\/>)/gi;
        let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
        let arr = this.oldData.match(imgReg);
        for (let i = 0; i < arr.length; i++) {
          let src = arr[i].match(srcReg); //获取图片地址
          if (src[1]) {
			temp.push("http://www.ansteelmro.com/"+src[1]);
          }
        }
      }
      return temp;
    },
    newUrls() {
      let temp = [];
      if (this.content) {
        let imgReg = /<img.*?(?:>|\/>)/gi;
        let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i;
        let arr = this.content.match(imgReg);
        for (let i = 0; i < arr.length; i++) {
			debugger
          let src = arr[i].match(srcReg); //获取图片地址
          if (src[1]) {
            temp.push("http://www.ansteelmro.com/"+src[1]);
          }
        }
      }
      return temp;
    },
    editorContext () {
      return this.$refs.editorText.quill
    }
  },
  created () {
    this.init()
  },
  mounted () {
    // this.fileUrl = fileUpdata.url
    this.fileConfig = {...fileUpdata.headers()}
  },
  methods: {
    /**
     * @functionName init
     * @description 页面初始化
     * @author 张航
     * @date 2020-09-09 08:40:06
     * @version V1.0.0
     */
    init () {
      this.getTableData()
    },
    /**
     * @functionName init
     * @description 富文本编辑器初始化
     * @author 张文韬
     * @date 2020-10-27 20:31:22
     * @version V1.0.0
     */
    initEditorData(data) {
      this.oldData = JSON.parse(JSON.stringify(data))
      this.content = data
    },
    /**
     * @functionName searchControlHandle
     * @param {Object} data 查询参数
     * @description 查询
     * @author 张航
     * @date 2020-09-08 15:01:26
     * @version V1.0.0
     */
    searchControlHandle (data) {
      this.searchFormData = data
      // console.log(data)
      this.refreshPageCurrent()
    },
    /**
     * @functionName refreshControlHandle
     * @param {Object} data 重置后的数据
     * @description 重置查询条件
     * @author 张航
     * @date 2020-09-08 17:01:51
     * @version V1.0.0
     */
    refreshControlHandle (data) {
      // console.log(data)
      this.searchFormData = data
    },
    /**
     * @functionName changeControlHeight
     * @param {String} height 控制区占用高度
     * @description 控制区高度变化
     * @author 张航
     * @date 2020-09-16 16:17:07
     * @version V1.0.0
     */
    changeControlHeight (height) {
      this.controlHeight = height
    },
    /**
     * @functionName insertControlHandle
     * @description 点击新增按钮
     * @author 张航
     * @date 2020-09-08 17:35:28
     * @version V1.0.0
     */
    insertControlHandle () {
      this.dialogFormCurrent = {}
      this.openDialog()
    },
    /**
     * @functionName changeTableSelectData
     * @param {Array} rows 选中数据
     * @description 表格选中数据改变
     * @author 张航
     * @date 2020-09-08 17:52:12
     * @version V1.0.0
     */
    changeTableSelectData (rows) {
      this.tableSelectData = rows
    },
    /**
     * @functionName checkTableSelectData
     * @return {Number} 返回结果
     * @description 方法描述
     * @author 张航
     * @date 2020-09-10 09:58:59
     * @version V1.0.0
     */
    checkTableSelectData () {
      if (this.tableSelectData.length === 0) {
        this.$alert('至少选择一条数据！', '提示', {
          confirmButtonText: '确定'
        })
      }
      return this.tableSelectData.length
    },
    /**
     * @functionName changePageSize
     * @param {Number} size 分页条数
     * @description 修改分页条数
     * @author 张航
     * @date 2020-09-08 17:57:06
     * @version V1.0.0
     */
    changePageSize (size) {
      this.pageData.pageSize = size
      this.getTableData()
    },
    /**
     * @functionName changePageCurrent
     * @param {Number} current 当前分页
     * @description 修改当前分页
     * @author 张航
     * @date 2020-09-08 18:02:03
     * @version V1.0.0
     */
    changePageCurrent (current) {
      this.pageData.pageNum = current
      this.getTableData()
    },
    /**
     * @functionName refreshPageCurrent
     * @description 重置当前分页
     * @author 张航
     * @date 2020-09-22 10:45:57
     * @version V1.0.0
     */
    refreshPageCurrent () {
      this.pageData.pageNum = 1
      this.getTableData()
    },
    /**
     * @functionName getTableData
     * @description 获取表格数据
     * @author 张航
     * @date 2020-09-08 17:59:45
     * @version V1.0.0
     */
    getTableData () {
      // console.log(this.searchData)
      getPlanList(this.searchData).then(res => {
        this.tableData = res.rows
        this.pageData.total = res.total
      })
    },
    getFileInfo (fileType, fileID) {
      getFileInfo(fileType,fileID).then(res=>{
        const fileInfo = {
          name: res.submittedFileName,
          url: res.url,
          id: res.id,
          fileType:res.fileType
        }
        this.fileList.push(fileInfo)
        // console.log(this.fileList)
      })
    },
    /**
     * @functionName updateTableHandle
     * @param {Object} row 当前行数据
     * @description 表格编辑按钮
     * @author 张航
     * @date 2020-09-14 16:43:26
     * @version V1.0.0
     */
    updateTableHandle (row) {
      this.dialogFormCurrent = { ...row }
      if (row.resourceId) {
        // this.getFileInfo(13, row.resourceId)
		var nameArr = row.filename.split(",");
		var urlArr = row.fileurl.split(",");
		for (var i = 0; i < nameArr.length; i++) {
			this.fileList.push({
				name: nameArr[i],
				url: urlArr[i],
				id: urlArr[i],
				fileType:row.fileType
			})
		}
	  }
      this.initEditorData(row.content)
      this.openDialog(1)
    },
	deleteTableHandle (row) {
	  
	  deletePlanNotice(row.id).then(
	    (res) => {
			this.getTableData()
	    }
	  )
	},
    /**
     * @functionName openDialog
     * @param {Number} type 编辑框类型;0:新增;1:编辑;
     * @description 打开编辑框
     * @author 张航
     * @date 2020-09-08 11:38:51
     * @version V1.0.0
     */
    openDialog (type = 0) {
      this.editDialogType = type
      this.editDialogShow = true
    },
    /**
     * @functionName closeDialog
     * @description 关闭编辑框
     * @author 张航
     * @date 2020-09-08 14:27:02
     * @version V1.0.0
     */
    closeDialog () {
      this.editDialogType = 0
      this.editDialogShow = false
      this.fileList = []
    },
    // 删除附件
    handleRemove (file, fileList) {
		debugger
      if (file && file.status === "success") {
        this.fileList = []
        this.dialogFormCurrent.resourceId = ''
      }
    },
    handleExceed(files, fileList) {
      this.$message.warning(`最多可上传 1 个附件，您已超限`)
    },
    handleUploadSuccess(res, file) {
      const curFile = {
        name: file.name,
        url:res.data,
        id:file.uid,
        fileType:res.data.fileType
      }
      this.fileList.push(curFile)
    },
    handleUploadError(res, file) {
      this.$message.error("文件上传失败，请重试")
    },
    beforeUpload(file) {
      const isLt500M = file.size / 1024 / 1024 < 500
      if (!isLt500M) {
        this.$message.error('上传附件大小不能超过 500MB!')
      }
      return isLt500M
    },
    /**
     * @functionName saveDialogData
     * @description 保存弹框数据
     * @author 张文韬
     * @date 2020-09-08 18:15:14
     * @version V1.0.0
     */
    saveDialogDataHandle () {
		var that =this;
      // console.log(this.fileList)
      // console.log(this.dialogForm.formData)
      this.$refs['dialogForm'].handleValidate((valid) => {
        if (!valid) {
          this.$message({
            message: '请检查表单填写内容',
            type: 'warning'
          })
          return
        }
        var parma = {
          ...this.dialogForm.formData,
        }
        // 附件
        if (that.fileList.length > 0) {
          let fileID = '';
          let filename = '';
          let fileurl = '';
		  for (var i = 0; i < that.fileList.length; i++) {
		  	if(i < that.fileList.length-1){
				fileID += that.fileList[i].url + ','
				filename += that.fileList[i].name + ','
				fileurl += that.fileList[i].url + ','
			}else{
				fileID += that.fileList[i].url
				filename += that.fileList[i].name
				fileurl += that.fileList[i].url
			}
		  }
          // console.log(this.fileList)
          parma = {
            ...parma,
            resourceId: fileID,
			filename:filename,
			fileurl:fileurl
          }
        }
        parma['content'] = this.content
		// parma['publishTime'] = moment('publishTime').format('YYYY-MM-DD HH:mm:ss')
		
		if(parma.id){
			editPlanNotice(parma).then(res => {
			  this.dialogForm.handleRefresh()
			  this.closeDialog()
			  this.refreshPageCurrent()
			  this.fileList = []
			  this.oldData = ''
			  this.content = ''
			  this.$message({
			    message: '保存成功',
			    type: 'success'
			  })
			})
		}else{
			insertPlanNotice(parma).then(res => {
			  this.dialogForm.handleRefresh()
			  this.closeDialog()
			  this.refreshPageCurrent()
			  this.fileList = []
			  this.oldData = ''
			  this.content = ''
			  this.$message({
			    message: '保存成功',
			    type: 'success'
			  })
			})
			
		}
        
      })
    },
    /**
     * @functionName cancelDialogData
     * @description 取消保存弹框数据
     * @author 张航
     * @date 2020-09-08 18:17:11
     * @version V1.0.0
     */
    cancelDialogDataHandle () {
      this.dialogForm.handleRefresh()
      this.closeDialog()
    },
    // 上传成功
    handleImgSuccess(res) {
      if (res && res.code == 0) {
        // 获取光标所在位置
        let length = this.editorContext.getSelection().index
        // 插入图片 res.url为服务器返回的图片地址
        this.editorContext.insertEmbed(length, "image", res.data)
        // 调整光标到最后
        this.editorContext.setSelection(length + 1)
      } else {
        this.$message.error("图片插入失败")
      }
      this.imageList = []
      this.loading = false
    },
    //  上传失败
    handleImgError(err) {
      this.$message.error("图片插入失败");
      this.loading = false
    },
    // 计算不需要了的图片
    diff(){
      let arr = this.oldUrls.filter(key=> !this.newUrls.includes(key))
      arr.forEach(url=>{
        let _url = Base64.encode(url)
        deleteFile(13,_url)
      })
    },
    loadingFn(){
      this.loading = true
    }
  }
}
</script>
<style lang="scss">
.box-card {
  margin: 4px;
  height: calc(100vh - 110px);
  .el-card__body {
    padding: 0;
  }
  .control-box{
    margin-bottom: 10px;
  }
}
.abc-header {
  color: #0000ff;
}
.editor-box-height{
  height: 270px;
}
.myQuillEditor-height {
  height: 200px;
}
</style>